package org.sgtools.gwt.delegate;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ServletConfigAware;
import org.springframework.web.context.ServletContextAware;

import com.google.gwt.user.client.rpc.RemoteService;


/**
 * This Spring controller delegates RPC requests to Spring services using
 * serviceResolver
 * 
 * @author Semyon Goryachkin
 * 
 */
@Controller
public class GwtDelegateController implements ServletContextAware,
		ServletConfigAware {

	private ServiceResolver serviceResolver;

	private GWTServiceHelperPrivate gwtServiceHelperPrivate;

	private ServletConfig servletConfig;

	private ServletContext servletContext;

	@RequestMapping
	void handleRPCRequest(HttpServletRequest request,
			HttpServletResponse response) {

		RemoteService service = serviceResolver.getService(request);
		GWTRemoteServiceServlet servlet = new GWTRemoteServiceServlet(service);
		servlet.setServletConfig(servletConfig);
		servlet.setServletContext(servletContext);
		try {

			if (gwtServiceHelperPrivate != null) {
				// Store the request & response objects in ServiceHelper.
				gwtServiceHelperPrivate.setServletData(request, response);
			}

			servlet.doPost(request, response);

		} finally {
			// Store null in ServiceHelper.
			if (gwtServiceHelperPrivate != null) {
				gwtServiceHelperPrivate.setServletData(null, null);
			}
		}

	}

	/**
	 * @param serviceResolver
	 */
	@Autowired
	public void setServiceResolver(ServiceResolver serviceResolver) {
		this.serviceResolver = serviceResolver;
	}

	/**
	 * @param gwtServiceHelperPrivate
	 */
	@Autowired(required = false)
	public void setGwtServiceHelperPrivate(
			GWTServiceHelperPrivate gwtServiceHelperPrivate) {
		this.gwtServiceHelperPrivate = gwtServiceHelperPrivate;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.context.ServletConfigAware#setServletConfig(javax
	 * .servlet.ServletConfig)
	 */
	@Override
	public void setServletConfig(ServletConfig servletConfig) {
		this.servletConfig = servletConfig;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.context.ServletContextAware#setServletContext
	 * (javax.servlet.ServletContext)
	 */
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

}
